package com.siwei.mes.controller.erp;

import com.siwei.mes.common.annotation.AnonymousAccess;
import com.siwei.mes.common.query.PageQuery;
import com.siwei.mes.common.result.ApiResult;
import com.siwei.mes.common.result.Json;
import com.siwei.mes.common.validator.PageGroup;
import com.siwei.mes.common.validator.UpdateGroup;
import com.siwei.mes.entity.dto.GenPrintInfoDto;
import com.siwei.mes.entity.dto.RwdextraExtendUpdateDto;
import com.siwei.mes.entity.erp.Rwdextra;
import com.siwei.mes.entity.erp.RwdextraEntity;
import com.siwei.mes.entity.erp.RwdextraExtend;
import com.siwei.mes.entity.erp.RwdextraExtendMaterials;
import com.siwei.mes.entity.sync.erp.ErpProject;
import com.siwei.mes.entity.vo.ExperimentVo;
import com.siwei.mes.mapper.syncErp.ErpProjectMapper;
import com.siwei.mes.service.erp.RwdextraExportService;
import com.siwei.mes.service.erp.RwdextraExtendService;
import com.siwei.mes.service.erp.RwdextraService;
import com.siwei.mes.service.experiment.ExperimentTaskService;
import com.siwei.mes.service.laboratory.ProduceHntService;
import com.siwei.mes.sync.config.SyncProcessorService;
import com.siwei.mes.sync.erp.entity.UpdateMix;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

/**
 * erp任务单相关
 *
 * @author linzi
 * @since 2024-07-29 15:40:02
 */
@Api(value = "erp任务单")
@Slf4j
@RestController
@RequestMapping("erpRwdextra")
public class ErpRwdextraController {
    @Resource
    private RwdextraService rwdextraService;
    @Resource
    private ExperimentTaskService experimentTaskService;
    @Resource
    private RwdextraExtendService rwdextraExtendService;
    @Resource
    private ProduceHntService produceHntService;
    @Resource
    private ErpProjectMapper erpProjectMapper;
    @Resource
    private RwdextraExportService rwdextraExportService;
    @Resource
    private SyncProcessorService syncProcessorService;

    @ApiOperation(value = "分页获取")
    @PostMapping("/page")
    public Json appPage(@RequestBody @Validated(PageGroup.class) PageQuery<Rwdextra, Rwdextra> query) {
        return Json.succ().data(rwdextraService.getPage(query));
    }

    @ApiOperation(value = "根据主键id获取")
    @GetMapping("loadByFrwdh")
    public Json loadByFrwdh(@RequestParam("frwdh") Integer frwdh) {
        return Json.succ().data(rwdextraService.loadByFrwdh(frwdh));
    }

    @ApiOperation(value = "根据主键id获取")
    @GetMapping("selectExperimentByFrwdh")
    public Json selectExperimentByFrwdh(@RequestParam("frwdh") Integer frwdh) {
        return Json.succ().data(rwdextraService.selectExperimentByFrwdh(frwdh));
    }

    @ApiOperation(value = "获取所有")
    @PostMapping("getAll")
    public Json getAll(@RequestBody Rwdextra entity) {
        return Json.succ().data(ApiResult.addList(rwdextraService.getAll(entity)));
    }

    @ApiOperation(value = "批量修改ERP任务单信息")
    @PostMapping("/updateBatchDetail")
    public Json updateBatchDetail(@RequestBody @Validated(UpdateGroup.class) RwdextraExtend entity) {
        assertTrue(entity.getFrwdhList() == null || entity.getFrwdhList().isEmpty(), "请选择对应的ERP任务单信息");
        List<RwdextraExtend> list = rwdextraExtendService.updateBatch(entity);
        for (RwdextraExtend extend : list) {
            String produceId = extend.getProduceId();//协会id
            if (StringUtils.isBlank(produceId)) {
                log.info("该任务单号：【{}】暂未上传到协会软件！", extend.getFrwdh());
                continue;
            }
            Long erpProjectId = extend.getErpProjectId();
            if (erpProjectId == null) {
                log.info("该任务单号：【{}】暂未设置工程", extend.getFrwdh());
                continue;
            }
            ErpProject erpProject = erpProjectMapper.loadById(erpProjectId);
            if (erpProject == null) {
                log.info("该工程信息不存在，对应任务单：【{}】，工程id：【{}】", extend.getFrwdh(), erpProjectId);
                continue;
            }
            if (StringUtils.isBlank(erpProject.getLaboratoryId())) {
                log.info("该工程为上传到协会，对应任务单：【{}】，工程id：【{}】", extend.getFrwdh(), erpProjectId);
                continue;
            }
            /**这里修改协会任务单工程信息*/
            try {
                produceHntService.updateProduceHntByErpProject(produceId, erpProject, true);
            } catch (Exception e) {
                log.error("该任务单：【{}】修改工程信息失败，失败原因：【{}】", extend.getFrwdh(), e.getMessage(), e);
            }
        }

        return Json.succ().data(new ApiResult());
    }

    @ApiOperation(value = "批量修改ERP任务单打印修改信息")
    @PostMapping("/updateBatchPrintDetail")
    public Json updateBatchPrintDetail(@RequestBody RwdextraExtend entity) {
        assertTrue(entity.getFrwdhList() == null || entity.getFrwdhList().isEmpty(), "请选择对应的ERP任务单信息");
        rwdextraExtendService.updateBatchPrint(entity);
        return Json.succ().data(new ApiResult());
    }

    @ApiOperation(value = "批量修改ERP任务单打印修改信息(工程名称+施工单位)")
    @PostMapping("/updateBatchPrintDetailRwdextra")
    public Json updateBatchPrintDetailRwdextra(@RequestBody RwdextraExtendUpdateDto rwdextraExtendUpdateDto) {
        assertTrue(rwdextraExtendUpdateDto.getFrwdhList() == null || rwdextraExtendUpdateDto.getFrwdhList().isEmpty(), "请选择对应的ERP任务单信息");
        rwdextraExtendService.updateBatchPrintDetailRwdextra(rwdextraExtendUpdateDto);
        return Json.succ().data(new ApiResult());
    }

    @ApiOperation(value = "根据任务单修改信息生成报告")
    @PostMapping("/generateReport")
    public Json generateReport(@RequestBody RwdextraExtend entity) {
        assertTrue(entity.getFrwdhList() == null || entity.getFrwdhList().isEmpty(), "请选择对应的ERP任务单信息");
        return Json.succ().data(rwdextraExtendService.generateReport(entity));
    }

    @ApiOperation(value = "根据主键id获取ERP任务单打印修改信息")
    @GetMapping("/getPrintByFrwdh")
    public Json getPrintByFrwdh(@RequestParam("frwdh") Integer frwdh) {
        return Json.succ().data(rwdextraService.loadByFrwdhExtend(frwdh));
    }

    @ApiOperation(value = "任务单生成资料")
    @GetMapping("genPrintInfo")
    public Json genPrintInfo(@RequestParam(required = false, name = "frwdh") Integer frwdh, @RequestParam(required = false, name = "frwdhs") String frwdhs) {
        List<Integer> frwdhList = new ArrayList<>();
        if (frwdh != null) {
            frwdhList.add(frwdh);
        }

        if (StringUtils.isNotBlank(frwdhs)) {
            String[] split = frwdhs.split(",");
            for (String s : split) {
                frwdhList.add(Integer.valueOf(s));
            }
        }
        GenPrintInfoDto genPrintInfoDto = new GenPrintInfoDto();
        genPrintInfoDto.setFrwdList(frwdhList);
        syncProcessorService.submitRequest(genPrintInfoDto);
        return Json.succ();
    }

    @ApiOperation(value = "根据试验委托id获取相关的任务单")
    @GetMapping("selectByExperimentId")
    public Json selectByExperimentId(@RequestParam("experimentId") Long experimentId) {
        return Json.succ().data(ApiResult.addList(experimentTaskService.selectByExperimentId(experimentId)));
    }

    @ApiOperation(value = "根据试验委托id获取相关的任务单")
    @PostMapping("selectByExperimentIdPage")
    public Json selectByExperimentIdPage(@RequestBody @Validated(PageGroup.class) PageQuery<ExperimentVo, ExperimentVo> query) {
        return Json.succ().data(ApiResult.addList(experimentTaskService.selectByExperimentIdPage(query)));
    }

    @ApiOperation(value = "任务单上传上海协会数据")
    @PostMapping("/uploadBatch")
    public Json uploadBatch(@RequestBody RwdextraEntity entity) {
        rwdextraService.uploadBatch(entity);
        return Json.succ().data(new ApiResult());
    }

    @ApiOperation("批量修改任务单扩展表打印json")
    @AnonymousAccess
    @GetMapping("updateBatchRwdextraJson")
    public Json updateBatchRwdextraJson() {
        rwdextraExtendService.updateBatchRwdextraJson();
        return Json.succ();
    }

    @ApiOperation("根据任务单号修改任务单扩展表氯离子含量")
    @AnonymousAccess
    @GetMapping("updateBatchLlzhl")
    public Json updateBatchLlzhl(@RequestParam("frwno") String frwno) {
        rwdextraExtendService.updateBatchLlzhl(frwno);
        return Json.succ();
    }

    @ApiOperation(value = "任务单导出")
    @PostMapping("/exportRwdextra")
    public Json exportRwdextra(@RequestBody Rwdextra entity, HttpServletRequest request) {
        return Json.succ().data(ApiResult.addList(rwdextraExportService.exportRwdextra(entity, request)));
    }

    @ApiOperation(value = "任务单导出报表")
    @PostMapping("/exportRwdextraPrint")
    public Json exportRwdextraPrint(@RequestBody Rwdextra entity) {
        return Json.succ().data(rwdextraExportService.exportRwdextraPrint(entity));
    }

    @ApiOperation("根据任务单号修改任务单扩展表绑定氯离子试验台账")
    @AnonymousAccess
    @GetMapping("updateBatchPrintLlzhl")
    public Json updateBatchPrintLlzhl() {
        rwdextraService.updateBatchPrintLlzhl();
        return Json.succ();
    }

    @PostMapping("updateMix")
    @ApiModelProperty(value = "修改配合比")
    public Json updateMix(@RequestBody UpdateMix updateMix) {
        assertTrue(updateMix.getFRwdh() == null, "ERP任务单id为空");
        /**
         * 任务单修改了配合比  需要生成一个试验委托  委托类型是更换配合比  2024-08-15 22:36:20  不考虑
         * 对应任务单下所有的小票 关联关系绑定   只生成快检和批检相关的  2024-08-15 22:36:25  不考虑
         * 全部都是抽检
         * 这个任务单之前的委托 需要关闭  修改pk_experiment_check_itemorder 中对应这个任务单的数据都要清除
         * */
        log.info("ERP通知修改任务单配合比，任务单号：【{}】，基准配比编号：【{}】", updateMix.getFRwdh(), updateMix.getFPhbNo());

        Rwdextra rwdextra = rwdextraService.selectByFrwdh(updateMix.getFRwdh());
        assertTrue(rwdextra == null, "ERP任务单信息不存在");
        /**统一用单列线程处理*/
        syncProcessorService.submitRequest(updateMix);
        return Json.succ();
    }


    @PostMapping("setMaterialsInfo")
    @ApiModelProperty(value = "设置任务单原材料信息")
    public Json setMaterialsInfo(@RequestBody RwdextraExtendMaterials entity) {
        assertTrue(entity.getFrwdh() == null, "任务单号为空");
        rwdextraExtendService.setMaterialsInfo(entity);
        return Json.succ();
    }

    @PostMapping("getMaterialsInfo")
    @ApiModelProperty(value = "获取任务单原材料信息")
    public Json getMaterialsInfo(@RequestBody RwdextraExtendMaterials entity) {
        assertTrue(entity.getFrwdh() == null, "任务单号为空");
        RwdextraExtendMaterials rwdextraExtendMaterials = rwdextraExtendService.getMaterialsInfo(entity);
        return Json.succ().data(rwdextraExtendMaterials);
    }
}
